package com.example.andylau96.res.Function.Cashier;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.method.NumberKeyListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.andylau96.res.DataBase.CashierDataBase;
import com.example.andylau96.res.Main.MainActivity;
import com.example.andylau96.res.R;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by AndyLau96 on 2016/12/14.
 */
public class orderFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemClickListener {
    private EditText order_id,coming_time,tables_num,people_num,text;
    private LinearLayout title;
    private ListView food_list;
    private SQLiteDatabase db;
    private Button ok;
    private ImageButton re;
    private TextView v;
    private int orderID=1;
    private SimpleAdapter adapter;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.order,container,false);
        title= (LinearLayout) view.findViewById(R.id.order_title);
        order_id= (EditText) view.findViewById(R.id.order_id);
        coming_time= (EditText) view.findViewById(R.id.coming_time);
        tables_num= (EditText) view.findViewById(R.id.order_tables);
        people_num= (EditText) view.findViewById(R.id.order_people);
        food_list= (ListView) view.findViewById(R.id.order_food_list);
        adapter=new SimpleAdapter(getActivity(),getData(),R.layout.choose_food_item,new String[]{"name","price","num"},
                new int[]{R.id.food_name,R.id.food_price,R.id.food_num});
        food_list.setAdapter(adapter);

        re= (ImageButton) view.findViewById(R.id.order_title_return);
        ok= (Button) view.findViewById(R.id.order_title_ok);
        re.setOnClickListener(this);
        ok.setOnClickListener(this);

        food_list.setOnItemClickListener(this);
        return view;
    }
    @Override
    public void onStart() {
        super.onStart();
        MainActivity.now=this;
        String theme=null;
        File file=new File("/data/data/com.example.andylau96.res/files/color.txt");
        try {
            InputStreamReader reader=new InputStreamReader(new FileInputStream(file),"UTF-8");
            BufferedReader br=new BufferedReader(reader);
            theme="";
            String temp=null;
            while((temp=br.readLine())!=null)
            {
                theme+=temp;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        title.setBackgroundColor(Color.parseColor(theme));

        File f=new File("/data/data/com.example.andylau96.res/files/orderid.txt");
        String t="";
        try {
            InputStreamReader reader=new InputStreamReader(new FileInputStream(f),"UTF-8");
            BufferedReader br=new BufferedReader(reader);
            String temp=null;
            while((temp=br.readLine())!=null)
            {
                t+=temp;
            }
            orderID=Integer.valueOf(t);
        } catch (Exception e) {
            e.printStackTrace();
        }
        order_id.setText(orderID+"");
    }
    public List<Map<String,Object>> getData()
    {
        List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
        db=new CashierDataBase(getActivity().getApplication()).getWritableDatabase();
        Cursor re=db.rawQuery("select *from ConsumeItem",null);
        String name[]=new String[100];
        double price[]=new double[100];
        int i=0;
        re.moveToFirst();
        while(!re.isAfterLast()) {
            name[i] = re.getString(re.getColumnIndex("itemName"));
            price[i] = re.getDouble(re.getColumnIndex("itemPrice"));
            Map<String,Object> map=new HashMap<>();
            map.put("name",name[i]);
            map.put("price",price[i]);
            map.put("num","0");
            list.add(map);
            i++;
            re.moveToNext();
        }
        re.close();
        db.close();
        return list;
    }

    @Override
    public void onClick(View view) {
        int id=view.getId();
        if(id==R.id.order_title_return)
        {
            getFragmentManager().popBackStack();
        }
        if(id==R.id.order_title_ok)
        {
            Calendar c=Calendar.getInstance();
            int year=c.get(Calendar.YEAR);
            int month=c.get(Calendar.MONTH)+1;
            int day=c.get(Calendar.DAY_OF_MONTH);
            String otime=year+"-"+month+"-"+day;

            String mid=order_id.getText().toString();
            String ctime=coming_time.getText().toString();
            String tables=tables_num.getText().toString();
            String people=people_num.getText().toString();

            String s="";
            int i=0;
            LinearLayout v= (LinearLayout) food_list.getChildAt(i);
            while(v!=null)
            {
                TextView num= (TextView) v.findViewById(R.id.food_num);
                s+=num.getText().toString()+"-";
                i++;
                v= (LinearLayout) food_list.getChildAt(i);
            }
            if(mid.length()==0||ctime.length()==0||tables.length()==0||people.length()==0)
                Toast.makeText(getActivity(),"请完整输入订餐信息!", Toast.LENGTH_SHORT).show();
            else
            {
                db=new CashierDataBase(getActivity().getApplication()).getWritableDatabase();
                db.execSQL("insert into OrderInfo values("+orderID+",'"+otime+"','"+ctime+"',"+tables+","+people+",'"+s+"')");
                orderID++;
                String p=orderID+"";
                try {
                    FileOutputStream crate = getActivity().openFileOutput("orderid.txt", getActivity().MODE_PRIVATE);
                    crate.write(p.getBytes());
                    crate.close();
                    Toast.makeText(getActivity(),"保存成功", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                }
                getFragmentManager().popBackStack();
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        v= (TextView) view.findViewById(R.id.food_num);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        text = new EditText(getActivity());
        text.setKeyListener(new NumberKeyListener() {
            @Override
            protected char[] getAcceptedChars() {
                return new char[]{'0','1','2','3','4','5','6','7','8','9'};
            }

            @Override
            public int getInputType() {
                return 0;
            }
        });
        builder.setTitle("请输入订购数量");
        builder.setIcon(android.R.drawable.ic_dialog_info);
        builder.setView(text);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String number=text.getText().toString();
                if(number.length()==0)
                    Toast.makeText(orderFragment.this.getActivity(), "请输入订购数量", Toast.LENGTH_SHORT).show();
                else
                {
                    v.setText(number);
                    dialogInterface.dismiss();
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        builder.show();
    }
}
